package com.lemon.core.validator.utils;

import com.lemon.core.base.exception.ValidateException;
import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * hibernate-validator校验工具类 参考文档：http://docs.jboss.org/hibernate/validator/5.4/reference/en-US/html_single/
 * 参考文档：https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#_code_groupsequenceprovider_code
 *
 * @author pan
 * @since 2017-03-15
 */
public class ValidatorUtils {

    private ValidatorUtils() {
    }

    private static Validator validator;

    static {
        validator = Validation.byProvider(HibernateValidator.class).configure().failFast(true).buildValidatorFactory()
                .getValidator();
    }

    /**
     * 校验对象
     *
     * @param object 待校验对象
     * @param groups 待校验的组
     * @throws ValidateException 校验不通过，则报ValidateException异常
     */
    public static void validate(Object object, Class<?>... groups) throws ValidateException {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            StringBuilder msg = new StringBuilder();
            for (ConstraintViolation<Object> constraint : constraintViolations) {
                msg.append(constraint.getMessage());
            }
            throw new ValidateException(msg.toString());
        }
    }
}
